<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <!-- 顶部搜索区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input
              @clear="getlist"
              clearable
              v-model="obj.query"
              placeholder="请输入内容"
              class="input-with-select"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getlist"
              ></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="adddialogVisible = true"
              >添加用户
            </el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 列表区 -->
      <el-table
        :data="userlist"
        style="width: 100%"
        border
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="180"
        ></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="用户状态">
          <!-- 作用域插槽 -->
          <template v-slot="{ row }">
            <!-- {{row.mg_state}} -->
            <el-switch
              v-model="row.mg_state"
              @change="change(row)"
              inactive-color="red"
              focus
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <!-- {{ row }} -->
            <el-button
              size="mini"
              :enterable="false"
              type="primary"
              icon="el-icon-edit"
              circle
              @click="getUserInfoById(row.id)"
            ></el-button>
            <el-button
              @click="del(row.id)"
              size="mini"
              :enterable="false"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="设置"
              placement="top"
            >
              <el-button
                size="mini"
                :enterable="false"
                type="warning"
                icon="el-icon-setting"
                circle
                @click="showset(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="obj.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="obj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="addformclose"
    >
      <!-- 添加用户表单 -->
      <span>
        <el-form
          :rules="addrules"
          ref="addformref"
          :model="addform"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addform.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addform.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addform.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addform.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>

      <!-- 下面确定取消按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserFrom">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog title="修改用户" :visible.sync="updialogVisible" width="50%">
      <!-- 修改用户表单 -->
      <span>
        <el-form
          :rules="addrules"
          ref="upformref"
          :model="upform"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input disabled v-model="upform.username"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="upform.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="upform.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>

      <!-- 下面确定取消按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="updialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="upUserFrom">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置用户 -->
    <el-dialog
      title="设置用户"
      :visible.sync="set"
      width="50%"
      close="setclose"
    >
      <!-- 添加用户表单 -->
      <span>
        <p>当前用户名:{{ userinfo.username }}</p>
        <p>当前角色名:{{ userinfo.role_name }}</p>
        <p>选择框:</p>
        <!-- 下拉组件 value是下拉框选中的id-->
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in rolelist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </span>

      <!-- 下面确定取消按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="set = false">取 消</el-button>
        <el-button type="primary" @click="setyes">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    // 自定义验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(value)
        ? callback()
        : callback(new Error("请输入合法的邮箱"));
    };
    // 自定义手机规则
    var checkTel = (rule, val, cb) => {
      return /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(val)
        ? cb()
        : cb(new Error("请输入合法手机号"));
    };
    return {
      // 添加用户的验证规则
      addrules: {
        username: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { validator: checkTel, trigger: "blur" }
        ]
      },
      obj: {
        query: "",
        //当前第几页
        pagenum: 1,
        // 当前每页展示的条数
        pagesize: 5
      },
      userlist: [],
      total: null,
      // 点击添加按钮定义先隐藏
      adddialogVisible: false,
      // 点击修改按钮定义先隐藏
      updialogVisible: false,
      //添加用户表单
      addform: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //修改用户表单
      upform: {},
      // set弹出框
      set: false,
      // 保存row里面的信息
      userinfo: {},
      //保存后台列表数据修改时用
      rolelist: [],
      // 下拉列表选中的值
      value: ""
    };
  },
  created() {
    this.getlist();
  },
  // mounted () {},
  computed: {},
  watch: {},
  methods: {
    //获取列表
    async getlist() {
      const { data: res } = await this.$http.get("users", { params: this.obj });
      if (res.meta.status != 200) return this.$message.error("获取失败");
      this.userlist = res.data.users;
      this.total = res.data.total;
      // console.log(this.userlist);
    },
    //改变switch状态
    async change(ob) {
      const { data: res } = await this.$http.put(
        `users/${ob.id}/state/${ob.mg_state}`
      );
      // console.log(res);
      if (res.meta.status != 200) {
        ob.mg_state = !ob.mg_state;
        return this.$message.error("更改状态失败");
      } else {
        this.$message.success("更改状态成功");
      }
    },
    //页码区
    //修改每页显示多少条
    handleSizeChange(val) {
      this.obj.pagesize = val;
      this.getlist();
      // console.log(`每页 ${val} 条`);
    },
    //修改当前展示第几页
    handleCurrentChange(val) {
      this.obj.pagenum = val;
      this.getlist();
      // console.log(`当前页: ${val}`);
    },
    // 搜索用户直接给点击按钮获取列表事件
    //添加变色
    tableRowClassName({ row, rowIndex }) {
      // console.log(rowIndex);
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    //关闭添加用户的对话框重置表达验证
    addformclose() {
      this.$refs.addformref.resetFields();
    },
    addUserFrom() {
      // 表达预校验
      this.$refs.addformref.validate(async boo => {
        // 信息没校验通过boo为false
        if (!boo) return this.$message.error("请填写完整信息");
        //发送请求添加用户
        const { data: res } = await this.$http.post("users", this.addform);
        if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败");
        } else {
          this.$message.success("添加成功");
          // 重新获取数据
          this.getlist();
          // 关闭对话框
          this.adddialogVisible = false;
        }
      });
    },
    //根据id查用户信息
    async getUserInfoById(id) {
      // 打开对话框
      this.updialogVisible = true;
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status != 200) {
        return this.$message.error("获取用户信息失败");
      }
      this.upform = res.data;
    },
    //提交修改用户信息
    upUserFrom() {
      //预校验
      this.$refs.upformref.validate(async boo => {
        // 信息没校验通过boo为false
        if (!boo) return this.$message.error("请填写完整信息");
        //发送请求添加用户
        const { data: res } = await this.$http.put(`users/${this.upform.id}`, {
          email: this.upform.email,
          mobile: this.upform.mobile
        });
        if (res.meta.status !== 200) {
          return this.$message.error("更新用户信息失败");
        } else {
          this.$message.success("更新用户信息成功");
          this.updialogVisible = false;
          this.getlist();
        }
      });
    },
    // 根据用户id删除用户
    async del(id) {
      // 操作询问,防止误删除
      const resu = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(res);
      if (resu === "cancel") return this.$message.info("取消删除成功");

      const { data: res } = await this.$http.delete(`users/${id}`);
      if (res.meta.status != 200) {
        return this.$message.error("删除用户信息失败");
      } else {
        this.$message.success("删除用户信息成功");
        this.getlist();
      }
    },
    // 点击设置按钮弹出对话框,在data中保存数据,在发送请求的时候可用
    async showset(rule) {
      // 点击设置行的对象信息存储在data的userinfo中
      this.userinfo = rule;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("失败");
      }
      this.rolelist = res.data;
      // console.log(res.data);
      // 弹出对话框
      this.set = true;
    },
    //清空下拉菜单的value值
    setclose() {
      this.value = "";
    },
    //点击确定按钮设置分配用户角色
    async setyes() {
      if (!this.value) return this.$message.error("失败");
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.value
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("失败");
      }
      this.$message.success("成功");
      // 重新渲染数据
      this.getlist();
      //关闭对话框
      this.set = false;
    }
  }
};
</script>

<style lang="less" scoped></style>
